package com.wl.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.errorprone.annotations.Var;
import com.wl.srb.core.mapper.DictMapper;
import com.wl.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelEictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    private DictMapper dictMapper;
    //数据列表
    List<ExcelDictDTO> list = new LinkedList<>();
    //每隔五秒批量存储一次数据
    private static final int BATCH_COUNT = 5;

    public ExcelEictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条数据{}", data);
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    private void saveData() {
        log.info("{}条数据存储到数据库", list.size());
        dictMapper.insertBatch(list);
        log.info("{}条数据存储到数据库成功", list.size());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后剩余的数据记录数不足BATCH时，我们最终一次性存储剩余数据
        saveData();
        log.info("所有解析完成");
    }
}
